package com.wxtl.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;

import com.wxtl.action.qo.LoginUser;
import com.wxtl.dao.base.HibernateBaseDao;
import com.wxtl.entity.User;
import com.wxtl.util.DataGridModel;
import com.wxtl.util.Page;
import com.wxtl.util.Status;

/**
 * UserDao
 * @author hc24
 *
 */
@Repository
public class UserDAO extends HibernateBaseDao {
	private static final Log log = LogFactory.getLog(UserDAO.class);
	
	/**
	 * 根据用户名，状态，级别等查询
	 * @param dgm
	 * @param user
	 * @return
	 */
	public Page query(DataGridModel dgm,User user){
		//构建hql
		StringBuilder hql=new StringBuilder();
		List<Object> params=new ArrayList<Object>();
		hql.append("from User u where 1=1");
		if(user.getUsername()!=null&&!"".equals(user.getUsername())){
			params.add("%"+user.getUsername()+"%");
			hql.append(" and u.username like ?");
		}
		if(user.getState()!=null&&user.getState()>0){
			params.add(user.getState());
			hql.append(" and u.state=?");
		}else{
			params.add(Status.STATE_DELETE);
			hql.append(" and u.state!=?");
		}
		return super.queryForList(hql.toString(), params.toArray(new Object[]{}), dgm.getPage(), dgm.getRows());
	}
	
	public User load(int userId){
		return (User) getHibernateTemplate().load(User.class, userId);
	}
	
	public void delete(int[] ids){
		//super.delete("user","userId", ids);
		//执行软删除
		super.deleteByMark("user", "userId", ids);
	}
	
	public User getUserById(int id){
		return (User) getHibernateTemplate().get(User.class, id);
	}
	
	public User getUserByNameAndPwd(LoginUser loginUser){
		String hql="from User u where u.username=? and u.password=?";
		List<User> list= getHibernateTemplate().find(hql, new Object[]{loginUser.getUsername(),loginUser.getPassword()});
		if(list.size()>0)
			return list.get(0);
		return null;
	}
	
	/**
	 * 主要用于用户名重复判断
	 * @param name
	 * @param userId
	 * @return
	 */
	public User getUser(String name,int userId){
		String hql="from User u where u.username=?";
		List<User> list = null ;
		if(userId>0){
			hql += " and u.userId!=?";
			list= getHibernateTemplate().find(hql, new Object[]{name,userId});
		}else{
			list= getHibernateTemplate().find(hql, new Object[]{name});
		}
		if(list.size()>0)
			return list.get(0);
		return null;
	}
	
}